﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ResourceEditor.Core;
using Editor.Properties;
using Microsoft.SqlServer.MessageBox;
using ResourceEditor.Core.ResourceDataObjects;
using ResourceEditor.Core.Search;

namespace Editor
{
    public partial class EditorString : UserControl
    {
        #region Properties
        private ResourceDataString Data { get; set; }
        private string PreviewsKey { get; set; }
        private Find FindWindow { get; set; }
        private SearchResults Result { get; set; }

        private Main MainForm
        {
            get
            {
                return (Main)base.ParentForm;
            }
        }
        #endregion

        #region Ctor
        public EditorString()
        {
            InitializeComponent();

            FindWindow = new Find();
            FindWindow.Next += FindWindow_Next;
        }

        #endregion

        #region Methods
        internal void Clear()
        {
            dgResourceData.Rows.Clear();
            Data = null;
        }

        private void Fill()
        {
            Fill(Data);
        }

        internal void Fill(ResourceDataString resource)
        {
            Clear();

            Data = resource;

            if (MainForm.ChangesMode)
            {
                ShowChanges();
            }
            else
            {
                ShowNormal();
            }
        }

        private void ShowChanges()
        {
            toolStrip1.Enabled = false;
            dgResourceData.Columns["Key"].ReadOnly = true;
            dgResourceData.Columns["Value"].Visible = false;
            dgResourceData.Columns["Values"].Visible = true;
            dgResourceData.Columns["State"].Visible = true;

            foreach (var item in Data)
            {
                if (item.State != ItemState.Original)
                {
                    DataGridViewRow row = dgResourceData.Rows[dgResourceData.Rows.Add()];
                    row.Cells["Key"].Value = item.Key;
                    DataGridViewComboBoxCell combo = (DataGridViewComboBoxCell)row.Cells["Values"];
                    if (item.State == ItemState.Deleted)
                    {
                        combo.Items.Add(item.Current);
                        combo.ReadOnly = true;
                        row.DefaultCellStyle.BackColor = Color.FromArgb(255, 81, 81);
                    }
                    else
                    {
                        combo.Items.AddRange(item.Items.ToArray());
                        if (item.State == ItemState.Added)
                        {
                            row.DefaultCellStyle.BackColor = Color.FromArgb(147, 253, 111);
                        }
                    }
                    combo.Value = combo.Items[0];
                    row.Cells["State"].Value = item.State.ToString();
                }
            }

            dgResourceData.Columns["Key"].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
            dgResourceData.Columns["State"].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
            dgResourceData.Columns["Values"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        }

        private void ShowNormal()
        {
            dgResourceData.Columns["Key"].ReadOnly = false;
            dgResourceData.Columns["Value"].Visible = true;
            dgResourceData.Columns["Values"].Visible = false;
            dgResourceData.Columns["State"].Visible = false;
            
            toolStrip1.Enabled = true;

            foreach (var item in Data)
            {
                if (item.State != ItemState.Deleted)
                {
                    dgResourceData.Rows.Add(item.Key, item.Current);
                }
            }

            dgResourceData.Columns["Key"].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
            dgResourceData.Columns["Value"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

        }

        private bool HasResult(ResourceFile searchIn, SearchStructure structure)
        {
            if (Result == null || Result.Search != structure)
            {
                Result = searchIn.Strings.Search(structure);

                if (Result == null)
                {
                    Program.Information(Resources.NoResult);
                    return false;
                }
            }

            return true;
        }

        private void SelectRow()
        {
            if (dgResourceData.SelectedRows.Count == 0)
            {
                SelectRow(Result.Results[0]);
            }
            else
            {
                bool find = false;
                foreach (int item in Result.Results)
                {
                    if (item > dgResourceData.SelectedRows[0].Index)
                    {
                        SelectRow(item);
                        find = true;
                        break;
                    }
                }

                if (!find)
                {
                    SelectRow(Result.Results[0]);
                }
            }
        }

        private void SelectRow(int index)
        {
            DataGridViewRow row = dgResourceData.Rows[index];
            row.Selected = true;
            dgResourceData.FirstDisplayedScrollingRowIndex = row.Index;
        }

        internal void Search(string name)
        {
            FindWindow.Show(name);
        }

        #endregion

        #region Events
        void FindWindow_Next(object sender, SearchStructureEventArgs e)
        {
            ResourceFile searchIn = Main.Manager[e.Structure.LookIn];

            if (HasResult(searchIn, e.Structure))
            {
                MainForm.SelectTab(ResourceType.String);
                MainForm.SelectResource(searchIn);
                SelectRow();
            }
        }

        private void tsNew_Click(object sender, EventArgs e)
        {
            if (Main.Current != null)
            {
                NewString newString = new NewString();
                if (newString.ShowDialog() == DialogResult.OK)
                {
                    Data.Add(newString.Key, newString.Value);
                    Fill();
                }
            }
        }

        private void dgResourceData_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
            Data.Delete(e.Row.Cells[0].Value.ToString());
            Result = null;
        }

        private void dgResourceData_UserAddedRow(object sender, DataGridViewRowEventArgs e)
        {
            Result = null;
        }

        private void dgResourceData_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (e.ColumnIndex == 0)
            {
                PreviewsKey = dgResourceData[e.ColumnIndex, e.RowIndex].Value.ToString();
            }
        }

        private void dgResourceData_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            string key = dgResourceData[0, e.RowIndex].Value.ToString();
            if (e.ColumnIndex == 0)
            {
                if (PreviewsKey != key)
                {
                    try
                    {
                        Data.ChangeKey(PreviewsKey, key);
                        Result = null;
                    }
                    catch (ArgumentException ex)
                    {
                        ExceptionMessageBox mb = new ExceptionMessageBox(ex);
                        mb.Show(this);

                        dgResourceData[e.ColumnIndex, e.RowIndex].Value = PreviewsKey;
                    }
                }
            }
            else
            {
                int columnIndex = MainForm.ChangesMode ? 2 : 1;
                object obj = dgResourceData[columnIndex, e.RowIndex].Value;
                if (obj != null)
                {
                    Data.ChangeItem(key, obj.ToString());
                    Result = null;
                }
            }
        }
        
        private void EditorString_Load(object sender, EventArgs e)
        {
            if (!DesignMode)
            {
                dgResourceData.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
                dgResourceData.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            }
        }
        #endregion    
    }
}
